// rollup.config.js
import path from 'path'
import json from "@rollup/plugin-json";
import nodeResolve from '@rollup/plugin-node-resolve'
import ts from 'rollup-plugin-typescript2'

// 根据环境变量的target属性, 获取对应模块中的 package.json
const packagesDir = path.resolve(__dirname, 'packages') // packages
// packageDir 打包的基准目录
const packageDir = path.resolve(packagesDir, process.env.TARGET) // packages/xxx

const resolve = (p) => path.resolve(packageDir, p)

const pkg = require(resolve('package.json'))
const name = path.basename(packageDir) // xxx

// 对打包类型做一个映射表, 根据package.json的formats来格式化需要打包的内容
const outputConfig = { // 自定义
    'esm-bundler': {
        file: resolve(`dist/${name}.esm-bundler.js`),
        format: 'es'
    },
    'cjs': {
        file: resolve(`dist/${name}.cjs.js`),
        format: 'cjs'
    },
    'global': {
        file: resolve(`dist/${name}.global.js`),
        format: 'iife' // 立即执行函数
    }
}

function createConfig(format, output) {
    output.name = options.name
    output.sourcemap = true // 生成sourcemap
    // 生成rollup配置
    return {
        input: resolve(`src/index.ts`),
        output,
        plugins: [
            json(),
            ts({
                tsconfig: path.resolve(__dirname, 'tsconfig.json')
            }),
            nodeResolve() // 解析第三方模块
        ]
    }
}

const options = pkg.buildOptions // 在package.json中自定义的属性

// rollup需要导出配置
export default options.formats.map(format => createConfig(format, outputConfig[format]))